package com.rose.doorto.footbathdoor.controler;

import com.rose.doorto.common.constant.AuthServerConstant;
import com.rose.doorto.common.constant.Constant;
import com.rose.doorto.footbathdoor.mapper.ProjectMapper;
import com.rose.doorto.footbathdoor.mapper.UserRoleMapper;
import com.rose.doorto.footbathdoor.pojo.Order;
import com.rose.doorto.footbathdoor.pojo.Project;
import com.rose.doorto.footbathdoor.pojo.User;
import com.rose.doorto.footbathdoor.service.OrderService;
import com.rose.doorto.footbathdoor.service.impl.OrderServiceImpl;
import com.rose.doorto.footbathdoor.service.impl.UserServiceImpl;
import com.rose.doorto.footbathdoor.util.PageUtils;
import com.rose.doorto.footbathdoor.vo.LoginVo;
import com.rose.doorto.footbathdoor.vo.RegVo;
import com.rose.doorto.footbathdoor.web.OrderWebController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户信息表 前端控制器
 * </p>
 *
 * @author lqc
 * @since 2024-07-08
 */
@Controller
@RequestMapping("/doorto/user")
public class UserController {

    @Autowired
    private UserServiceImpl userServiceImpl;

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private OrderWebController webController;
    @Autowired
    private OrderServiceImpl orderServiceImpl;

    /**
     * 跳转登录页
     * @return
     */
    @RequestMapping("/loginTo")
    public String loginTo(){
        return "login.html";
    }

    /**
     * 登录
     * @return
     */
    @PostMapping("/login")
    public String login(LoginVo loginVo, Model model, HttpSession session){
        if (loginVo.getUsername() != null && loginVo.getPassword()!=null){
            User login = userServiceImpl.login(loginVo);
            if (login != null){
                //登录失败会被异常处理器处理
                //登录成功后要保存会话信息,返回主页面
                //第一次使用session,命令浏览器保存卡号,JESSIONID这个cookie
                //以后浏览器访问哪个网站就会带上这个网站的cookie
                //子域之间: door.com  xxxx.door.com   xxxx.door.com
                //TODO 1.默认发的令牌作用域为当前域,解决不了子域之间的共享问题
                //TODO 2.使用JSON的序列化方式来序列化数据对象到redis中
                session.setAttribute(AuthServerConstant.LOGIN_USER_KEY,login);
                System.out.println("成功");
                System.out.println(session.getAttribute(AuthServerConstant.LOGIN_USER_KEY)+"session里存进去了"+AuthServerConstant.LOGIN_USER_KEY);
                int roleByUserId = userRoleMapper.getRoleByUserId(login.getId());
//                if (roleByUserId>1){
//                    //说明当前登录用户的身份不止一个,允许用户自主选择身份进行登录
//                }else {
//                    //如果是只要普通用户这一种身份,则直接跳转到首页
//                    //List<Project> list = projectMapper.selectList(null);
//                    List<Project> list = projectMapper.findAll();
//                    model.addAttribute("projects",list);
//                    model.addAttribute("user",login);
//                    //项目页面
//                    return "index.html";
//                }

                //TODO 地址,下单时间,备注,金额,下单人名称可见,其余不可见,手机号只有接单后才可见
                if (login.getIdentification() == 1){
                    //如果是只要普通用户这一种身份,则直接跳转到首页
                    //List<Project> list = projectMapper.selectList(null);
                    List<Project> list = projectMapper.findAll();
                    model.addAttribute("projects",list);
                    model.addAttribute("user",login);
                    //项目页面
                    return "index.html";
                }else {
                    String pageNum = "1";
                    String pageSize = "5";
                    Map<String, Object> params = new HashMap<>();
                    params.put(Constant.PAGE, pageNum);
                    params.put(Constant.LIMIT, pageSize);
                    PageUtils page = orderService.getOrderList(params);
                    List<Order> list = (List<Order>) page.getList();
                    for (Order order : list) {
                        List<Order> pageList = (List<Order>) page.getList();
                        List<Order> orders = orderServiceImpl.hidePhoneNumber(order.getPhone());
                        for (Order orderList : orders) {
                            for (Order teacherOrder : pageList) {
                                teacherOrder.setPhone(orderList.getPhone());
                            }
                        }
                        page.setList(pageList);
                    }
                    model.addAttribute("page",page);
                    return "/orderIndex.html";
                }
            }
        }else {
            return "reg.html";
        }
        return "";
    }

    //TODO ip数据库应该是集合类型，MD5加密、换ip登录等问题后期改
    /**
     * 注册
     * @return
     */
    @GetMapping("/regist")
    public String regist(RegVo regVo) throws UnknownHostException {

        if (regVo!=null){
            User user = userServiceImpl.getMobile(regVo.getMobile());
            if (user ==null){
                // 获取本机的InetAddress实例
                InetAddress ip = InetAddress.getLocalHost();
                String ipAddress = ip.getHostAddress(); // 获取IP地址
                regVo.setLogin_ip(ipAddress);
                int regist = userServiceImpl.regist(regVo);
                if (regist == 1){
                    return "index.html";
                }else {
                    return "操作失败";
                }
            }else {
                return "该手机号已注册";
            }
            }

        return "reg.html";
    }

    /**
     * 用户注销功能
     * @param request
     * @return
     */
    @GetMapping("logout")
    public String logout(HttpServletRequest request) throws IOException {
        //从request中获取当前登录对象
        HttpSession session = request.getSession();
        if (session!=null){
            //从会话中清楚用户信息
            session.invalidate();;
        }
        //重定向到登录页面
        return "/login.html";
    }
    /**
     * 跳转注册页
     * @return
     */
    @RequestMapping("/getToRegist")
    public String getToRegist(){
        return "reg.html";
    }

    /**
     * 管理我的地址
     * @return
     */
    @GetMapping("/receivingPage")
    public String receivingPage() {
        return "receiving.html";
    }
}
